/**
 * 
 */
package com.eppear.jpfm.framework.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName BeanMapUtil
 * @Description map和bean互转工具
 * @author JianFeng Zhang(张建锋)
 * @date 2017年4月11日 下午3:20:23
 * 
 */
public class BeanMapUtil {

	private static final Logger log = LoggerFactory.getLogger(BeanMapUtil.class);

	/**
	 * @Title mapToBean
	 * @Description 把Map转成Bean对象
	 * @author JianFeng Zhang(张建锋)
	 * @data 2017-04-11 下午3:44:28
	 * @param map
	 * @param bean
	 * @return
	 */
	public static void mapToBean(Map<String, ? extends Object> map, Object obj) {

		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			Object value;

			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				//key的首字母大写的情况也考虑了进去
				String Key = toUpperCaseFirstOne(key);
				value = null;

				if (map.containsKey(key)) {
					value = map.get(key);
				} else if (map.containsKey(Key)) {
					value = map.get(Key);
				}
				if (value != null) {
					String valueType = property.getPropertyType().getSimpleName();
					Method setter = property.getWriteMethod();
					if (valueType.equals("long")) {
						setter.invoke(obj, Long.valueOf((String) value));
					} else {
						setter.invoke(obj, value);
					}

				}
			}

		} catch (Exception e) {
			log.error("Map转Bean出错:{} " + e);
		}
	}

	public static Map<String, Object> beanToMap(Object bean) {
		if (bean == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(bean);
					map.put(key, value);
				}

			}
		} catch (Exception e) {
			log.error("Bean转Map出错:{}", e);
		}

		return map;
	}

	// 首字母转小写
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0)))
					.append(s.substring(1)).toString();
	}

	// 首字母转大写
	public static String toUpperCaseFirstOne(String s) {
		if (Character.isUpperCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0)))
					.append(s.substring(1)).toString();
	}

}
